from django.shortcuts import render, redirect,reverse,HttpResponse
from .models import User
from django.views.generic import View
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.conf import settings
from django.core.mail import send_mail
from django.contrib import auth
from django.contrib.auth import login
from django.shortcuts import render_to_response
import re
from celery_tasks.tasks import send_active_email
from django.shortcuts import render
from django.http import request
from django.http.response import HttpResponse, JsonResponse
# 导入缓存对象
import json
from django.shortcuts import render
from django.http import request
from django.http.response import HttpResponse, JsonResponse
from .forms import RegisterForm
# 导入缓存对象
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from django.core.cache import cache
import random
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from df_user import aliyunsms,restful
# 首页显示验证码

# def register(request):
#     return render(request,'register.html')
def register_handle(request):
    username=request.POST.get("user_name")
    password=request.POST.get("pwd")
    email=request.POST.get("email")
    allow=request.POST.get("allow")
    phone=request.POST.get("phone")

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        """如果出现该异常说明用户名不存在，则让user对象为空"""
        user = None
    # 如果user对象存在，则表示用户名已存在，返回错误提示信息
    if user:
        return render(request, "register.html", {"error_msg": "用户名已存在"})

    if not all([username,password,email]):
        return render(request,"register.html",{"error_msg":"数据不完整"})
    if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$",email):
        return render(request,"register.html",{"error_msg":"邮箱格式不正确"})
    if allow !="on":
        return render(request,"register.html",{"error_msg":"请勾选同意"})
    user = User.objects.create_user(username=username, email=email, password=password ,phone=phone)
    serializer = Serializer(settings.SECRET_KEY, 3600)  # 有效期1小时
    info = {"confirm": user.id}
    token = serializer.dumps(info).decode()
    # subject = "海马生鲜欢迎你"  # 邮件标题
    # message = ''# 邮件正文
    # sender = settings.EMAIL_FROM # 发件人
    # receiver = [email] # 收件人
    # html_message = """
    #      <h1>%s 恭喜您成为海马生鲜注册会员</h1><br/><h3>请您在1小时内点击以下链接进行账户激
    # 活</h3><a
    # href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
    # """ % (username, token, token)
    # send_mail(subject, message, sender, receiver, html_message=html_message)
    user.is_active = 0
    user.save()
    send_active_email(email,username,token)
    return redirect(reverse("goods:index"))
def index(request):
    """显示首页"""
    return render(request, "index.html")
class Registerview(View):
    '''注册'''
    def get(self,request):
        '''显示注册页面'''
        # hashkey = CaptchaStore.generate_key()
        # image_url = captcha_image_url(hashkey)
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form':register_form})
    def post(self,request):
        '''处理用户数据'''
class ActiveView(View):
    def get(self,request,token):
        '''进行用户激活'''
        serializer=Serializer(settings.SECRET_KEY,3600)
        try:
            info=serializer.loads(token)
            #获取用户id
            user_id=info['confirm']
            #根据用户id 获取用户对象
            user=User.objects.get(id=user_id)
            #设置该用户对象中的is_active字段的值为1
            user.is_active=1
            user.save()
            #使用反向解析跳转到登录页
            return redirect(reverse("goods:login"))
        except SignatureExpired as e:
            #出现异常链接失败
            return HttpResponse("激活链接已经过期")
class loginView(View):
    """登录"""
    def get(self,request):
        """显示登录页"""
        if 'username' in request.COOKIES:
            username = request.COOKIES.get("username")
            checked = "checked"
        else:
            username = ''
            checked = ''

        return render(request, "login.html", {"username": username, "checked": checked})
    def post(self,request):
        """登录校检"""
        username=request.POST.get("username")
        password=request.POST.get("pwd")
        user=auth.authenticate(username=username,password=password)#正确返回user对象，不正确返回None
        response = redirect(reverse("goods:index"))
        # 判断用户是否记勾选记住用户名
        remember = request.POST.get("remember")
        username = request.COOKIES.get('username', '')
        if user is not None:
            #用户名密码正确
            if user.is_active:
                #用户已激活
                login(request,user)
                if remember == "on":
                    # 表示勾选了,将用户名保存在cookie中
                    response.set_cookie("username", username, max_age=7 * 24 * 3600)
                else:
                    # 删除cookie
                    response.delete_cookie("username")
                # 重定向到主页
                return response
            else:
                #用户未激活
                return render(request,"login.html",{"error_msg":"账户未激活"})
        else:
            #用户名或密码错误
            return render(request,"login.html",{"error_msg":"用户名或密码错误"})
# def page_not_found(request, exception):  # 注意点 ①
#     return render(request, '404.html')
#
# # 500
# def page_error(request):
#     return render(request, '500.html')
# def yindex(request):
#     #生成验证码表单
#     register_form = RegisterForm()
#     return render(request, 'register.html', {'register_form': register_form})
def img_refresh(request):
    if not request.is_ajax():
        return HttpResponse('不是Ajax请求')
    new_key=CaptchaStore.generate_key()
    to_json_response={
        'hashkey':new_key,
        'image_url':captcha_image_url(new_key)
    }
    return HttpResponse(json.dumps(to_json_response))
def img_check(request):
    print('验证用户输入的图片验证码')
    if request.is_ajax():
        cs=CaptchaStore.objects.filter(response=request.GET.get('code'),
                                       hashkey=request.GET.get('hashkey'))
        print(cs)
        if cs:
            json_data = {'status': 1}
        else:
            json_data = {'status': 0}
        return JsonResponse(json_data)
    else:
        # raise Http404
        json_data = {'status': 0}
        return JsonResponse(json_data)
def test_redis(request):
    # 存储数据
    cache.set('name','tom',20)#该值的有效期为20s
    # 判断Redis中是否存在
    print(cache.has_kay("name"))    #包含:true
    # 获取
    print(cache.get("name"))    #返回:tom 无返回Null
    return  HttpResponse("测试Redis")
#!/usr/bin/env python
#coding=utf-8
def send_sms(phone,code):
    client = AcsClient('mxTYXZ4QDQecJQDN', 'znxNezmm4zfA9kPyqx1WrpznjCaJFT', 'cn-hangzhou')
    #phone = '17600950805'
    #aa= '222222'
    code = "{'code':%s}"%(code)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https') # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')
    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('PhoneNumbers', phone)
    request.add_query_param('SignName', '北网')
    request.add_query_param('TemplateCode', 'SMS_162738723')
    request.add_query_param('TemplateParam',code )
    response = client.do_action(request)
    # python2: print(response)
    print(str(response, encoding = 'utf-8'))
    return str(response, encoding = 'utf-8')
def get_code(n=6,alpha=True):
    s = '' # 创建字符串变量,存储生成的验证码
    for i in range(n):# 通过for循环控制验证码位数
        num = random.randint(0,9)# 生成随机数字0-9
        if alpha: # 需要字母验证码,不用传参,如果不需要字母的,关键字alpha=False
            upper_alpha = chr(random.randint(65,90))
            lower_alpha = chr(random.randint(97,122))
            num = random.choice([num,upper_alpha,lower_alpha])
            s = s + str(num)
        return s
def sms_send(request):
    # http://localhost:8000/duanxin/duanxin/sms_send/?phone=18434288349
    # 1 获取手机号
    phone = request.GET.get('phone')
    print(phone)
    # 2 生成6位验证码
    code = aliyunsms.get_code(6, False)
    # 3 缓存到Redis
    cache.set(phone,code,60) #60s有效期
    print('判断缓存中是否有:',cache.has_key(phone))
    print('获取Redis验证码:',cache.get(phone))
    # 4 发短信
    result = aliyunsms.send_sms(phone, code)
    print(result)
    return HttpResponse(result)
def  check_sms(request):
    #/duanxin/check_sms/?phone=xxx&code=xx
    # 1 后去电话和code
    phone = request.GET.get('phone')
    code = request.GET.get('code')
    # 2 获取Resis中code
    cache_code = cache.get(phone)
    # 3 判断
    if code == cache_code:
        return  restful.ok("OK", data=None)
    else:
        return restful.page_error("False", data=None)